package com.reflect.test;

import com.reflect.entity.Student;

import java.lang.reflect.Constructor;

/**
 * @author wzm
 * @create 2023-04-06 10:31
 */

//反射调用构造函数创建对象
public class RefTest03 {
    public static void main(String[] args) throws Exception {
     //获取类的字节码文件
       Class clazz = Class.forName("com.reflect.entity.Student");

       //获取空参构造方法
        Constructor constructor = clazz.getConstructor();
        //调用空参构造方法创建对象
        Student student = (Student) constructor.newInstance();
        student.id=11;
        System.out.println("student = " + student);

        //获取私有的带参数的构造函数
        Constructor con2 = clazz.getDeclaredConstructor(String.class, int.class);

        //临时修改私有的访问权限  暴力反射 private可以被访问
        con2.setAccessible(true);

        //调用私有的两个参数的构造函数 传参
        Student student1 = (Student) con2.newInstance("张三", 18);
        System.out.println("student1 = " + student1);
    }

}
